package com.sise.studentInfoSystem.controller;

import com.sise.studentInfoSystem.domain.*;
import com.sise.studentInfoSystem.mapper.ExtraPointsMapper;
import com.sise.studentInfoSystem.mapper.PrehensiveMapper;
import com.sise.studentInfoSystem.mapper.ProfrssionalSkillsMapper;
import com.sise.studentInfoSystem.mapper.StudentMapper;
import com.sise.studentInfoSystem.template.OssTemplate;
import com.sise.studentInfoSystem.vo.ProfrssionalSkillsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @Author zzp
 * @Desc
 * @Date 2020/7/4
 */
@Controller
public class StudentController {

    @Autowired
    OssTemplate ossTemplate;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    PrehensiveMapper prehensiveMapper;

    @Autowired
    ExtraPointsMapper extraPointsMapper;

    @Autowired
    ProfrssionalSkillsMapper profrssionalSkillsMapper;

    @RequestMapping("/toInfo")
    public String toInfo() {
        return "stu_info";
    }

    @RequestMapping("/toCreativeAbility")
    public String toCreativeAbility() {
        return "outstands/stu_creativeAbility";
    }

    @RequestMapping("/toOrganizationManagement")
    public String toOrganizationManagement() {
        return "outstands/stu_organizationManagement";
    }

    @RequestMapping("/toStylisticAbility")
    public String toStylisticAbility() {
        return "outstands/stu_stylisticAbility";
    }

    @RequestMapping("/toSocialPractice")
    public String toSocialPractice() {
        return "outstands/stu_socialPractice";
    }


    /**
     * 删除已经提交的专业技能
     * @param session
     * @return
     */
    @RequestMapping("/delProfessionalAlreadySub")
    @ResponseBody
    public String delProfessionalAlreadySub(HttpSession session) {
        // 获取当前登入用户的id
        TStudent user = (TStudent) session.getAttribute("loginStu");
        String stuId = user.getStuId();
        int effectRows = profrssionalSkillsMapper.delById(stuId);
        if (effectRows==0){
            return "error";
        }
        return "ok";
    }

    /**
     * 跳转专业技能页面
     * @return
     */
    @RequestMapping("/toProfessionalAbility")
    public String toProfessionalAbility(HttpSession session,Model model) {
        // 准备一个小计的值
        float count = 0L;

        // 获取当前登入用户的id
        TStudent user = (TStudent) session.getAttribute("loginStu");
        if (user == null) {
            return "outstands/stu_professionalAbility";
        }
        String stuId = user.getStuId();

        // 准备一个返回前端数据的vo对象
        List<ProfrssionalSkillsVO> profrssionalSkillsVOS = new ArrayList<ProfrssionalSkillsVO>();

        List<ProfrssionalSkills> professionals = profrssionalSkillsMapper.findProfrssionalSkillsByStuId(stuId);
        for (ProfrssionalSkills professional : professionals) {
            // 初始化一个vo
            ProfrssionalSkillsVO profrssionalSkillsVO = new ProfrssionalSkillsVO();
            profrssionalSkillsVO.setStuId(professional.getStuId());
            profrssionalSkillsVO.setItemImg(professional.getItemImg());
            profrssionalSkillsVO.setStatus(professional.getStatus());
            profrssionalSkillsVO.setMsg(professional.getMsg());

            // 同过id查询加分条目
            Integer itemId = professional.getItemId();
            TExtraPoint textraPoint = null;
            if(itemId == 0){
                textraPoint = new TExtraPoint();
                textraPoint.setItemName("暂无");
                textraPoint.setItemScore(0L);
            }else {
                textraPoint = extraPointsMapper.findItemByItemId(itemId);
            }


            // 将加分项名称和对加分数设置到vo
            profrssionalSkillsVO.setItemName(textraPoint.getItemName());
            profrssionalSkillsVO.setItemScore(textraPoint.getItemScore());

            count = count + textraPoint.getItemScore();

            profrssionalSkillsVOS.add(profrssionalSkillsVO);
        }

        // 计算一下预计得分
        float expectScore = (float) (count * 0.25);

        // 将vo对象设置到model中
        model.addAttribute("skillsVO",profrssionalSkillsVOS);
        model.addAttribute("count",count);
        model.addAttribute("expectScore",expectScore);

        return "outstands/stu_professionalAbility";
    }

    /**
     * 跳转学业表现页面
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/toAcademic")
    public String toAcademic(Model model, HttpSession session) {
        TStudent loginStu = (TStudent) session.getAttribute("loginStu");
        String stuId = loginStu.getStuId();
        TAcademic academic = studentMapper.findAcademicById(stuId);
        if (academic == null) {
            academic = new TAcademic();
            academic.setStatus("0");
        }
        model.addAttribute("academic", academic);
        return "stu_academicPerformance";
    }

    /**
     * 跳转行为表现提交页面
     *
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/toBehavior")
    public String toBehavior(HttpSession session, Model model) {

        TStudent tStudent = (TStudent) session.getAttribute("loginStu");

        List<Prehensive> prehensiveList ;
        prehensiveList = prehensiveMapper.findPrehensive(tStudent.getStuId());

        float score = 0;
        float sum = 0;
//        System.out.println("==========================================");
//        System.out.println(prehensiveList==null?"null":"nonull");
//        System.out.println(prehensiveList.size());
//        System.out.println(prehensiveList.isEmpty());
        if (prehensiveList != null){
            for (int i = 0; i < prehensiveList.size(); i++) {
                sum += prehensiveList.get(i).getPoint();
            }
        }

        score = ((100 - sum) * 0.1) < 0 ? 0 : (float) ((100 - sum) * 0.1);
        model.addAttribute("prenhensiveList", prehensiveList);
        model.addAttribute("score", score);
        return "stu_behaviorPerformance";
    }

    /**
     * 上传行为表现
     *
     * @param re
     * @param session
     * @return
     */
    @RequestMapping("/doBehaviorPerformance")
    @ResponseBody
    public Map<String, String> doBehaviorPerformance(HttpServletRequest re, HttpSession session) {
        Map<String, String> reMap = new HashMap<String, String>();
        int item = 10;
        List<Prehensive> prehensiveList = new LinkedList<Prehensive>();
        TStudent user = (TStudent) session.getAttribute("loginStu");
        if (user == null) {
            reMap.put("state", "0");
            reMap.put("msg", "用户登录过期！");
            return reMap;
        } else {
            String StuId = user.getStuId();
            String prefContent = "itemContent";
            String prefPoint = "itemPoint";
            // 删除旧数据
            prehensiveMapper.deletePrehensive(StuId);
            boolean flag = false;
            for (int i = 1; i <= 10; i++) {
                String content = re.getParameter(prefContent + Integer.toString(i));
                String point = re.getParameter(prefPoint + Integer.toString(i));
                if (content == null || point == null) {
                    break;
                } else if (content != null || point != null) {
                    Prehensive prehensive = new Prehensive();
                    prehensive.setStuId(StuId);
                    prehensive.setPrehensivePerformanceEvaluationContent(content);
                    prehensive.setPoint(Float.parseFloat(point));
                    prehensive.setStatus(1);

                    prehensiveMapper.InsetPrehensive(prehensive);
                    prehensiveList.add(prehensive);

                    flag = true;
                }
                reMap.put("state", "1");
                reMap.put("msg", "数据提交成功！");
            }
//            System.out.println(prehensiveList.toString());
            if(flag==false){
                // 给行为表现表添加一个默认几零几
                Prehensive prehensive = new Prehensive();
                prehensive.setStuId(user.getStuId());
                prehensive.setPrehensivePerformanceEvaluationContent("无违规记录");
                prehensive.setPoint(0L);
                prehensive.setStatus(1);
                prehensiveMapper.InsetPrehensive(prehensive);
                reMap.put("state", "1");
                reMap.put("msg", "数据提交成功！");
            }
            return reMap;
        }
    }

    /**
     * 上传专业技能，证明图片地址及信息
     *
     * @param body
     * @param req
     * @param session
     * @return
     */
    @PostMapping("/uploadProfessionalInfo")
    @ResponseBody
    public String uploadProfessionalInfo(@RequestBody String body, HttpServletRequest req, HttpSession session) {

        //封装map数据
        Map<String, Object> reMap = new HashMap<String, Object>();
        //获取当前用户
        TStudent student = (TStudent) session.getAttribute("loginStu");
        if (student == null) {
            //登录超时
            reMap.put("status", 0);
            reMap.put("msg", "登录超时！");
            return "error";
        }

        // addScoreItem-1=初级会计证&addScoreLevel-1=无&addScoreImgSrc-1=http://atcrowdfunding-zzp.oss-cn-shenzhen.aliyuncs.com/studentInfoSystem/1/prove/professionalProve/a78d5d037f944c5b8a58ade864aeef9a_201515-158211451517f1.jpg
        // &addScoreItem-2=高校计算机等级考试&addScoreLevel-2=一级&addScoreImgSrc-2=http://atcrowdfunding-zzp.oss-cn-shenzhen.aliyuncs.com/studentInfoSystem/1/prove/professionalProve/824f415bccd14e32bbd115bde6a88128_ee5066fc8021ff231147f2c9be3787dd.jpg

        String preItem = "addScoreItem-";
        String preLevel = "addScoreLevel-";
        String preImgSrc = "addScoreImgSrc-";

        int num = 0;
        for (int i = 1; i <= 10; i++) {

            String item = req.getParameter(preItem + i);
            String level = req.getParameter(preLevel + i);
            String img = req.getParameter(preImgSrc + i);

            if (item != null && level != null && img != null) {

                level = level.equals("无") ? "" : level;
                String itemName = item + level;

                int itemId = 0;
                Object objNum = extraPointsMapper.findItemIDByItemName(itemName);
                if (objNum != null) {
                    itemId = Integer.parseInt(objNum.toString());
                }

//                System.out.println("itemID:" + itemId);

                // 存储数据：
                ProfrssionalSkills bean = new ProfrssionalSkills();
                bean.setStuId(student.getStuId());
                bean.setItemId(itemId);
                bean.setItemImg(img);
                bean.setStatus(1);
//                System.out.println(bean);

                num = num + profrssionalSkillsMapper.insertProfrssionalSkill(bean);

            } else {
                break;
            }
        }
        reMap.put("status", 1);
        reMap.put("msg", "提交成功!");

        return "success";
    }


    /**
     * 修改学业表现信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/reEdit")
    @ResponseBody
    public String reEdit(HttpSession session) {
        TStudent loginStu = (TStudent) session.getAttribute("loginStu");
        String stuId = loginStu.getStuId();
        int result = studentMapper.delAcademicById(stuId);
        if (result != 1) {
            return "error";
        }
        return "ok";
    }

    /**
     * 上传学业表现信息
     *
     * @param academic
     * @return
     */
    @PostMapping("/uploadAcademic")
    @ResponseBody
    public String uploadAcademic(TAcademic academic,HttpSession session,@RequestBody String body) {
//        System.out.println("body:"+body);
//        System.out.println("academic:"+academic);

        // 从session中获取当前登入的学生id
        TStudent student = (TStudent) session.getAttribute("loginStu");
        String stuId = student.getStuId();
        // 将旧数据删除
        studentMapper.delAcademicById(stuId);
        // 将新数据写入数据库
        int resultCode = studentMapper.uploadAcademic(academic);
        if (resultCode != 1) {
            return "error";
        }
        return "ok";
    }

    /**
     * 修改密码
     *
     * @param newPwd
     * @param session
     * @return
     */
    @PostMapping("/updatePwd")
    @ResponseBody
    public String updatePwd(String newPwd, HttpSession session) {
        TStudent loginStu = (TStudent) session.getAttribute("loginStu");
        String stuId = loginStu.getStuId();
        int resultCode = studentMapper.updatePwdById(newPwd, stuId);
        if (resultCode != 1) {
            return "error";
        }
        return "ok";
    }

    /**
     * 更新用户签名
     *
     * @param newSignature
     * @param session
     * @return
     */
    @PostMapping("/updateSignature")
    @ResponseBody
    public String updateSignature(String newSignature, HttpSession session) {
        TStudent loginStu = (TStudent) session.getAttribute("loginStu");
        String stuId = loginStu.getStuId();
        int resultCode = studentMapper.updateSignatureById(newSignature, stuId);
        if (resultCode != 1) {
            return "error";
        }
        loginStu.setSignature(newSignature);
        session.setAttribute("loginStu", loginStu);
        return "ok";
    }

    /**
     * 更新用户爱好
     *
     * @param newHobby
     * @param session
     * @return
     */
    @PostMapping("/updateHobby")
    @ResponseBody
    public String updateHobby(String newHobby, HttpSession session) {
        TStudent loginStu = (TStudent) session.getAttribute("loginStu");
        String stuId = loginStu.getStuId();
        int resultCode = studentMapper.updateHobbyById(newHobby, stuId);
        if (resultCode != 1) {
            return "error";
        }
        loginStu.setHobby(newHobby);
        session.setAttribute("loginStu", loginStu);
        return "ok";
    }

    /**
     * 修改密码： 检查旧密码
     *
     * @param oldPwd
     * @param session
     * @return
     */
    @PostMapping("/checkOldPwd")
    @ResponseBody
    public String checkOldPwd(String oldPwd, HttpSession session) {
        TStudent loginStu = (TStudent) session.getAttribute("loginStu");
        String stuId = loginStu.getStuId();
        String originalPwd = studentMapper.findPwdById(stuId);
//        System.out.println(oldPwd);

        if (originalPwd.equals(oldPwd)) {
            return "ok";
        }
        return "error";
    }

    /**
     * 上传学生头像
     *
     * @param file
     * @param session
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadHeadImg")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException {
        TStudent loginStu = (TStudent) session.getAttribute("loginStu");
        String originalFilename = file.getOriginalFilename();
        String last = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);

        // 支持的图片类型
        String imgArr[] = {"bmp", "jpg", "png", "tif", "gif",
                "pcx", "tga", "exif", "fpx", "svg",
                "psd", "cdr", "pcd", "dxf", "ufo",
                "eps", "ai", "raw", "WMF", "webp"};
        boolean flag = false;
        for (String extents : imgArr) {
            if (extents.equalsIgnoreCase(last)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            return "failed";
        }

        String path = "";
        if (file != null) {
            path = ossTemplate.upload(file.getInputStream(), file.getOriginalFilename(), loginStu.getStuId() + "/studentHeadImg");
        }


        loginStu.setHeadImg(path);

        studentMapper.updateImgByID(path, loginStu.getStuId());

//        System.out.println(path);

        return path;
    }

    /**
     * 上传专业技能图片证明
     *
     * @param
     * @return
     */
    @PostMapping("/uploadProfessionalProve")
    @ResponseBody
    public String uploadProfessionalProve(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException {
        TStudent loginStu = (TStudent) session.getAttribute("loginStu");
        String originalFilename = file.getOriginalFilename();
        String last = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);

        // 图片类型
        String imgArr[] = {"bmp", "jpg", "png", "tif", "gif",
                "pcx", "tga", "exif", "fpx", "svg",
                "psd", "cdr", "pcd", "dxf", "ufo",
                "eps", "ai", "raw", "WMF", "webp"};
        boolean flag = false;
        for (String extents : imgArr) {
            if (extents.equalsIgnoreCase(last)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            return "failed";
        }

        String path = "";
        if (file != null) {
            path = ossTemplate.upload(file.getInputStream(), file.getOriginalFilename(), loginStu.getStuId() + "/prove/professionalProve");
        }

//        System.out.println(path);

        return path;
    }
}
